package test.converter;

import org.apache.commons.beanutils.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * Created by aceyin on 15/7/15.
 */
public class DateConverter implements Converter {

    public static final String DATE_FORMAT = "yyyy-MM-dd";
    public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    @Override
    public <T> T convert(Class<T> aClass, Object value) {
        if (value == null || !(value instanceof String)) {
            return null;
        }
        SimpleDateFormat df;
        String str = (String) value;
        if (str.length() == DATE_FORMAT.length()) {
            df = new SimpleDateFormat(DATE_FORMAT);
        } else {
            df = new SimpleDateFormat(DATETIME_FORMAT);
        }
        try {
            return (T) df.parse(str);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }
}
